package com.slcf.util;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;

import org.apache.commons.codec.Charsets;
import org.apache.commons.codec.digest.Md5Crypt;

import com.google.common.hash.Hashing;

/**
 * http请求工具类
 * @author zhangze
 * 
 */
public class HttpUtil {
	/** 连接超时时间 **/
	public static final int CONNECTION_TIMEOUT = 5 * 1000;
	public static final int READ_TIMEOUT = 5 * 1000;
	public static final String CHARSET = "UTF-8";
	
	public static String sendGet(String url) {
		return sendGet(url, CHARSET);
	}
	
	/**
	 * 使用Get方式获取数据
	 * 
	 * @param url
	 *            URL包括参数，http://HOST/XX?XX=XX&XXX=XXX
	 * @param charset
	 * @return
	 */
	public static String sendGet(String url, String charset) {
		String result = "";
		BufferedReader in = null;
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setConnectTimeout(CONNECTION_TIMEOUT);
			connection.setReadTimeout(READ_TIMEOUT);
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 建立实际的连接
			connection.connect();
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(
					connection.getInputStream(), charset));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}


	/**
	 * POST请求，Map形式数据
	 * 
	 * @param url
	 *            请求地址
	 * @param param
	 *            请求数据
	 * @param charset
	 *            编码方式
	 */
	public static String sendPostUrl(String url, String param, String charset) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setConnectTimeout(CONNECTION_TIMEOUT);
			conn.setReadTimeout(READ_TIMEOUT);
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			conn.setRequestProperty("Content-Type", "application/json");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), charset));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}
	
	
	public static void main(String[] args) {
		//HttpUtil.sendPostUrl("http://localhost/calfTrader-traderCenter-api/financeMessage/finaMenologyFind.do", "currentPage=1&newsDate=20170205", "utf-8");
//		for (int i = 0; i < 50; i++) {
//			String result = HttpUtil.sendGet("http://140.207.168.154:8088/tpp/wd/sendMessage?loanTerm=14&loanType=善真贷", "utf-8");
//			System.out.println(result);
//		}
		String result1 = "";
		for (int i = 0; i < 300; i++) {
			String loanNo = "YZ-TEST-" + new Date().getTime();
			String tradeCode = "TRADE-TEST-" + new Date().getTime();
			// 4、验签错误 md5(Key+ companyName + effectDate +  requestTime)
			String hashString = "7149D7A3EDE945F54A87D1F49C8979ED" + loanNo + "20170613134813" 
					+ "意真金融" + tradeCode;
			String sign = Hashing.md5().hashString(hashString, Charsets.UTF_8).toString();
			
			
			String s = " {\"accountManageAmount\": 0,"+
				    "\"accountManageRate\": 0,"+
				    "\"advancedRepaymentRate\": 0,"+
				    "\"applyTime\": \"20170613134814\","+
				    "\"auditMap\": ["+
				    "    {"+
				    "        \"auditDate\": \"20170613134814\","+
				    "        \"auditType\": \"通过\""+
				    "    }"+
				    "],"+
				    "\"bankMap\": {"+
				     "   \"bankName\": \"中国农业银行\","+
				    "    \"cardNo\": \"6228480038780777777\""+
				    "},"+
				    "\"companyName\": \"意真金融\","+
				    "\"custMap\": {"+
				       " \"credentialsCode\": \"370126199009090035\","+
				       " \"credentialsType\": \"身份证\","+
				       " \"custCode\": \"yz0000001\","+
				       " \"custName\": \"贾立义\","+
				       " \"education\": \"暂无\","+
				      "  \"marriage\": \"暂无\","+
				     "   \"mobile\": \"18353165952\""+
				    "},"+
				    "\"loanAmount\": 1000,"+
				    "\"loanDesc\": \" test-意真21216\","+
				    "\"loanNo\": \""+loanNo+"\","+
				    "\"loanTerm\": 21,"+
				    "\"loanType\": \"善真贷\","+
				    "\"monthlyManageAmount\": 0,"+
				    "\"monthlyManageRate\": 0,"+
				    "\"overdueRepaymentRate\": 0,"+
				    "\"repaymentCycle\": 1,"+
				    "\"repaymentList\": ["+
				        "{"+
				           " \"advanceCleanupTotalAmount\": 1000,"+
				          "  \"currentTerm\": 1,"+
				         "   \"expectRepaymentDate\": \"20170627\","+
				        "    \"repaymentInterest\": 0,"+
				       "     \"repaymentPrincipal\": 1000,"+
				      "      \"repaymentTotalAmount\": 1000"+
				     "   }"+
				    "],"+
				    "\"repaymentMethod\": \"到期还本付息\","+
				    "\"requestTime\": \"20170613134813\","+
				    "\"sign\": \""+sign+"\","+
				    "\"termUnit\": \"天\","+
				    "\"tradeCode\": \""+tradeCode+"\","+
				    "\"yearIrr\": 0,"+
				    "\"interfaceType\": \"保存优选项目\"}";
//			System.out.println(s);
			String result = HttpUtil.sendPostUrl("http://localhost:8084/openservice/saveProject",s, "utf-8");
//			System.out.println(loanNo + "|" +result);
			
			result1 += loanNo + ",";
		}
		System.out.println(result1 );
		
	}
}